﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DigitalPlatform.Common.Mangaer;
using DigitalPlatform.Components;
using DigitalPlatform.Entities;
using DigitalPlatform.IDAL;
using DigitalPlatform.Models;
using Prism.Commands;
using Prism.Mvvm;

namespace DigitalPlatform.ViewModels
{
    public class ConfigViewModel : BindableBase
    {
        private readonly ILocalDataAccess _localDataAccess;

        public ConfigViewModel(ILocalDataAccess localDataAccess)
        {
            this._localDataAccess = localDataAccess;
            init();
        }

        #region func
        private void init()
        {
            Cmd_CompDrag = new DelegateCommand<object>(Btn_CompDrag);
            Cmd_Cancel = new DelegateCommand<object>(Btn_Cancel);
            Cmd_SaveChanges = new DelegateCommand<object>(Btn_SaveChanges);
            Cmd_Selected = new DelegateCommand<object>(Btn_Selected);
            //初始化组件列表
            ThumbList = new ObservableCollection<ThumbModel>(_localDataAccess.QueryEntities<ThumbsEntity>().Result
                .ToList()
                .GroupBy(x => x.Category)
                .Select(x => new ThumbModel()
                {
                    Header = x.Key,
                    Children = new ObservableCollection<ThumbItemModel>(x.Select(y => new ThumbItemModel()
                    {
                        TargetType = y.Target_Type,
                        Height = int.Parse(y.H),
                        Width = int.Parse(y.W),
                        Icon = y.Icon,
                    }))
                }));
            //初始化加载已保存的设备信息
            _localDataAccess.QueryEntities<DeviceEntity>().Result.ToList().ForEach(x =>
            {
                DeviceList.Add(new DeviceItemModel()
                {
                    DeviceType = x.DeviceTypeName,
                    Height = double.Parse(x.H),
                    Width = double.Parse(x.W),
                    DeviceNum = x.DeviceNum,
                    X = double.Parse(x.X),
                    Y = double.Parse(x.Y),
                    Z = int.Parse(x.Z),
                    DeleteCommand = new DelegateCommand<object>((x) =>
                    {
                        DeviceList.Remove((x as ComponentBase).DataContext as DeviceItemModel);
                    })
                });
            });
        }
        #endregion
        #region props

        private DeviceItemModel _currentDevice;

        public DeviceItemModel CurrentDevice
        {
            get { return _currentDevice; }
            set { SetProperty(ref _currentDevice, value); }
        }


        public ObservableCollection<ThumbModel> ThumbList { get; set; } = new();
        public ObservableCollection<DeviceItemModel> DeviceList { get; set; } = new();
        public string Title => "设备组态配置";
        #endregion


        #region command
        public ICommand Cmd_CompDrag { get; set; }
        public ICommand Cmd_Cancel { get; set; }
        public ICommand Cmd_SaveChanges { get; set; }
        public ICommand Cmd_Selected { get; set; }
        #endregion


        #region func


        /// <summary>
        /// 按钮按下即为选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Btn_Selected(object sender)
        {
            var obj = sender as MouseButtonEventArgs;
            //检查当前选中项是否有效，有效则先取消其选中状态
            if (CurrentDevice != null)
                CurrentDevice.IsSelected = false;
            //再次判断选中的类型是否是组件元素，是则设置其选中状态
            if ((obj.Source as FrameworkElement).DataContext.GetType() == typeof(DeviceItemModel))
            {
                CurrentDevice = (obj.Source as FrameworkElement).DataContext as DeviceItemModel;
                CurrentDevice.IsSelected = true;
            }//如果不是组件元素，取消当前选中项的选中状态
            else
            {
                if (CurrentDevice != null)
                    CurrentDevice.IsSelected = false;
            }
        }
        public void Btn_CompDrag(object obj)
        {
            DragDrop.DoDragDrop(obj as Border, obj, DragDropEffects.Copy);
        }
        //当控件拖至ItemControl后事件
        public void ItemControlDrop(object sender, DragEventArgs e)
        {
            var border = (Border)e.Data.GetData(typeof(Border));
            var datacontext = border.DataContext as ThumbItemModel;

            var point = e.GetPosition((IInputElement)e.Source);
            DeviceList.Add(new DeviceItemModel()
            {
                X = point.X - border.Width / 2,
                Y = point.Y - border.Height / 2,
                DeviceType = datacontext.TargetType,
                DeviceNum = DateTime.Now.ToString("yyyyMMddHHmmss"),
                Width = datacontext.Width,
                Height = datacontext.Height,
                DeleteCommand = new DelegateCommand<object>((x) => { DeviceList.Remove((x as ComponentBase).DataContext as DeviceItemModel); })
            });
        }
        public void Btn_Cancel(object obj)
        {
            (obj as Window).DialogResult = false;
        }

        public async void Btn_SaveChanges(object obj)
        {
            try
            {
                await _localDataAccess.RemoveAll<DeviceEntity>();
                await _localDataAccess.SaveEntities<DeviceEntity>(DeviceList.Select(x => new Entities.DeviceEntity()
                {
                    X = x.X.ToString(),
                    Y = x.Y.ToString(),
                    Z = x.Z.ToString(),
                    W = x.Width.ToString(),
                    H = x.Height.ToString(),
                    DeviceNum = x.DeviceNum,
                    DeviceTypeName = x.DeviceType
                }).ToList());
                (obj as Window).DialogResult = true;
            }
            catch (Exception e)
            {
                (obj as Window).DialogResult = false;
            }

        }
        #endregion
    }
}
